package com.tianji.learning.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.tianji.common.constants.CacheConstant;
import com.tianji.common.utils.JsonUtils;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.listener.LearningRecordSyncToMysqlListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;

@Slf4j
@Component
@ConditionalOnProperty(name = "tj.delay.type", havingValue = "springtask", matchIfMissing = false)
public class LearningRecordSyncToMysqlTask {

    @Autowired
    private LearningRecordSyncToMysqlListener syncToMysqlListener;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Scheduled(cron = "*/20 * * * * ?")
    public void syncToMysql(){
        log.info("开始执行定时任务，扫描学习记录。。。");
        // 读取redis中所有的record的key
        Set<String> keys = redisTemplate.opsForSet().members(CacheConstant.LEARNING_RECORD_KEYS);
        if(CollUtil.isEmpty(keys)){
            log.info("没有要同步的数据");
            return;
        }
        for (String key : keys) {
            String json = redisTemplate.opsForValue().get(key);
            LearningRecord redisRecord = JsonUtils.toBean(json, LearningRecord.class);
            // 对比redis中的最新的时间和当前时间的差，如果超过了20秒，则同步到数据库
            // 因为如果视频在持续播放，每隔15秒更新一下redis，redis的时间与当前时间最多相差15秒
            LocalDateTime updateTime = redisRecord.getUpdateTime();
            long now = System.currentTimeMillis();
            if(updateTime.plusSeconds(20).isAfter(LocalDateTimeUtil.of(now))){
                // 说明还在播放
                continue;
            }
            // 同步到数据库
            syncToMysqlListener.onLearningRecordSyncToMysql(redisRecord);
            // 删除key
            redisTemplate.opsForSet().remove(CacheConstant.LEARNING_RECORD_KEYS, key);
        }
    }
}
